using System.Reflection;
using Ellwood.Manage.Models.Entity;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace Ellwood.Manage.MentApi.Utility.InitDatabaseExt;

/// <summary>
/// 初始化数据库
/// </summary>
public static class InitDatabaseExt
{

    /// <summary>
    /// 初始化数据库
    /// </summary>
    /// <param name="builder"></param>
    public static void InitDatabase(this WebApplicationBuilder builder)
    {
        // 保存在系统中获取的功能数据：---页面功能，---菜单功能，---按钮功能
        List<SysMenu> MenuList = new List<SysMenu>();
        Assembly asm = Assembly.GetExecutingAssembly();
        IEnumerable<Type> controlleractionlist = asm.GetTypes()
            .Where(type => typeof(ControllerBase)
                .IsAssignableFrom(type));
        
        foreach (var controller in controlleractionlist)
        {
            if (controller.IsDefined(typeof(FunctionAttribute), true))
            {
                FunctionAttribute? attribute = controller.GetCustomAttribute<FunctionAttribute>();
                Guid guid = Guid.NewGuid();
                SysMenu sysMenu = new SysMenu()
                {
                    Id = guid,
                    ParentId = default,
                    MenuText = attribute?.GetDescription(),
                    MenuType = attribute is null ? (int)MuType.Page : (int)attribute.GetMuType()
                };
                MenuList.Add(sysMenu);

                var methodList=controller.GetMethods()
                    .Where(m => m.IsDefined(typeof(FunctionAttribute), true));
                
                foreach (var method in methodList)
                {
                    FunctionAttribute? childAttribute = method.GetCustomAttribute<FunctionAttribute>();
                    SysMenu childMenu = new SysMenu()
                    {
                        Id = Guid.NewGuid(),
                        ParentId = guid,
                        FullName = $"{controller.FullName},{method.Name}",
                        MenuText = childAttribute?.GetDescription(),
                        MenuType = childAttribute is null ? (int)MuType.Btn : (int)childAttribute.GetMuType(),
                        ControllerName = controller.Name.ToLower().Replace("controller",""),
                        ActionName = method.Name.ToLower()
                    };
                    MenuList.Add(childMenu);
                }
            }

        }
        
        // 数据库连接信息
        string? connectionStr = builder.Configuration.GetConnectionString("connStr");
        
        if (string.IsNullOrWhiteSpace(connectionStr))
        {
            throw new Exception("请配置数据库连接字符串");
        }
        
        ConnectionConfig connection = new ConnectionConfig()
        {
            ConnectionString = connectionStr, 
            DbType = DbType.SqlServer,
            IsAutoCloseConnection = true
        };

        using (SqlSugarClient client = new SqlSugarClient(connection))
        {
            // 删除数据库--如果有就删除
            client.DbMaintenance.CreateDatabase();
    
            Assembly assembly=Assembly.LoadFile(
                Path.Combine(AppContext.BaseDirectory,"Ellwood.Manage.Models.dll"));

            Type[] typeArray = assembly.GetTypes()
                .Where(t=>!t.Name.Equals("BaseEntity") &&t.Namespace.Equals("Ellwood.Manage.Models.Entity"))
                .ToArray();
    
            client.CodeFirst.InitTables(typeArray);
            // client.Insertable(menuList).ExecuteCommand();
            client.Insertable(MenuList).ExecuteCommand();
        }

    }

}